/*
 * @lc app=leetcode.cn id=700 lang=typescript
 *
 * [700] 二叉搜索树中的搜索
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

//  思路：迭代
//  利用BST的特性，类似二分搜索进行遍历

//  复杂度：O(n) O(n)

function searchBST(root: TreeNode | null, val: number): TreeNode | null {
    if (!root) return null
    if (root.val === val) return root
    if (root.val < val) return searchBST(root.right, val)
    if (root.val > val) return searchBST(root.left, val)
    return null
};
// @lc code=end

import { TreeNode } from "./type"
const root = TreeNode.buildTree([4, 2, 7, 1, 3, null, null])
console.log(TreeNode.printTree(searchBST(root, 2)))
